next up previous contents index
Next: Methods Up: Objects Previous: Fields

Constructors and destructors

 

As can be seen in the syntax diagram for an object declaration, Free Pascal supports constructors and destructors. You are responsible for calling the constructor and the destructor explicitly when using objects.

The declaration of a constructor or destructor is as follows:


Constructors and destructors

syntdiag2238

syntdiag2242

syntdiag2246

syntdiag2250

A constructor/destructor pair is required if you use virtual methods.

In the declaration of the object type, you should use a simple identifier for the name of the constuctor or destructor. When you implement the constructor or destructor, you should use a qulified method identifier, i.e. an identifier of the form objectidentifier.methodidentifier.

Free Pascal supports also the extended syntax of the New and Dispose procedures. In case you want to allocate a dynamic variable of an object type, you can specify the constructor's name in the call to New. The New is implemented as a function which returns a pointer to the instantiated object. Consider the following declarations:
listing2084
Then the following 3 calls are equivalent:
listing2086
and
listing2088
and also
listing2090
In the last case, the compiler will issue a warning that you should use the extended syntax of new and dispose to generate instances of an object. You can ignore this warning, but it's better programming practice to use the extended syntax to create instances of an object.

Similarly, the Dispose procedure accepts the name of a destructor. The destructor will then be called, before removing the object from the heap.

In view of the compiler warning remark, the now following Delphi approach may be considered a more natural way of object-oriented programming.


next up previous contents index
Next: Methods Up: Objects Previous: Fields

Michael Van Canneyt
Fri Sep 25 09:15:40 MEST 1998